﻿#region Imports
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using CommonUtilities.Enums;
using CommonUtilities.Extensions;
using Microsoft.Win32;
#endregion

namespace CommonUtilities.Util
{
    public static class RegistryOperator
    {
        #region Declarations
        public static SimpleDelegate OnInvalidOperation { get; set; }
        #endregion

        #region Properties

        #endregion

        #region Events

        #endregion

        #region Methods
        /// <summary>
        /// 
        /// </summary>
        /// <seealso cref="http://commandwindows.com/runline.htm" />
        /// <example>Option-2: Create shortcut; copy it to %systemroot%; DONE</example>
        public static void CheckRunRegistry(SimpleDelegate op)
        {
            RegistryKey keyTopLevel = Registry.LocalMachine;
            RegistryKey keyAppPaths = keyTopLevel.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\App Paths", true);
            RegistryKey keyBulkRenamer = null;

            Assembly executingAssembly = Assembly.GetExecutingAssembly();
            string keyName = Application.ExecutablePath;
            keyName = keyName.FormatPathExtnCase(eExtnCase.LCase);

            if (!keyAppPaths.GetSubKeyNames().Where(key => key == keyName).Any())
            {
                keyBulkRenamer = keyAppPaths.CreateSubKey(keyName);
                keyBulkRenamer.SetValue("", Application.ExecutablePath);
                if (!op.IsNull()) op();
            }
            else
            {
                keyBulkRenamer = keyAppPaths.OpenSubKey(keyName, true);
                if (!keyBulkRenamer.IsNull())
                {
                    if (keyBulkRenamer.GetValue("").ToString() != Application.ExecutablePath)
                    {
                        keyBulkRenamer.SetValue("", Application.ExecutablePath);
                        if (!op.IsNull()) op();
                    }
                }
            }

            keyTopLevel.Close();
            keyAppPaths.Close();
            keyBulkRenamer.Close();
        }
        #endregion
    }
}
